import {Request} from "express";
import Constant from "@src/util/constant";
import {clone, getMeta} from "@src/util/util";
import dictSql from "@src/sql/dictSql";
import literatureSql from "@src/sql/literatureSql";

// 添加
const add = async (req: Request) => {
  const {category_id, file_id, cover_id, name} = req.body;
  // 文件参数是否正确
  if (!(await literatureSql.isFileId(file_id)) || !((await literatureSql.isFileId(cover_id)))) {
    return Constant.FILE_ID_ERROR;
  }
  // 是否重名
  if (await literatureSql.isLiteratureName(name)) {
    return Constant.ADD_ERROR;
  }
  // 是否存在分类
  if (!(await dictSql.isCategoryId(category_id))) {
    return {data: Constant.CATEGORY_ERROR};
  }
  // 创建文献
  return await literatureSql.add(req);
};

// 更新
const update = async (req: Request) => {
  const {category_id, file_id, cover_id, name} = req.body;
  const {id} = req.params;
  // 是否存在该文献
  if (!(await literatureSql.isLiterature(id))) {
    return Constant.LITERATURE_NOT_ERROR;
  }
  // 文件参数是否正确
  if (!(await literatureSql.isFileId(file_id)) || !((await literatureSql.isFileId(cover_id)))) {
    return Constant.FILE_ID_ERROR;
  }
  // 是否重名
  if (await literatureSql.isLiteratureName(name)) {
    return Constant.ADD_ERROR;
  }
  // 是否存在分类
  if (!(await dictSql.isCategoryId(category_id))) {
    return Constant.CATEGORY_ERROR;
  }
  return await literatureSql.update(req);
};

// 列表
const list = async (page: number, size: number, filters: any) => {
  // 从第几条开始查询
  const offset = (page - 1) * size;
  //查询
  const {
    count,
    rows,
    dictData,
  } = await literatureSql.list(offset, size, filters);
  // 成功
  let resObj = clone(Constant.DEFAULT_SUCCESS);
  // 分页
  const meta = getMeta(count, page, size);
  return {
    ...resObj,
    meta,
    data: rows,
    type_id: dictData.type_id,
  };
};

// 更新首页推荐
const updateRecommend = async (id: string, recommend: number) => {
  // 是否存在该文献
  if (!(await literatureSql.isLiterature(id))) {
    return Constant.LITERATURE_NOT_ERROR;
  }
  return await literatureSql.updateRecommend(id, recommend);
};

// 更新是否上架
const updateGrounding = async (id: string, grounding: number) => {
  // 是否存在该文献
  if (!(await literatureSql.isLiterature(id))) {
    return Constant.LITERATURE_NOT_ERROR;
  }
  return await literatureSql.updateGrounding(id, grounding);
};


// 文献详情
const detail = async (id: string) => {
  // 是否存在该文献
  if (!(await literatureSql.isLiterature(id))) {
    return Constant.LITERATURE_NOT_ERROR;
  }
  return await literatureSql.detail(id);
};


// 前台查询
const frontList = async (page: number, size: number, id:string,filters:any) => {
  const offset = (page - 1) * size;
  const {count, rows} = await literatureSql.frontList(offset, size,id,filters);
  // 分页
  const meta = getMeta(count, page, size);
  return {
    ...Constant.DEFAULT_SUCCESS,
    meta,
    data: rows,
  };
};
export default {
  add,
  update,
  list,
  updateRecommend,
  updateGrounding,
  detail,
  frontList,
};